package api

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"encoding/pem"
	"fmt"
	"io"
	"net/http"
	"strings"
)

const (
	RSA_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs0Xk9lvInsuI3mel6d9l+cqLgsKAYB7FkSYN07oBm8umRL6BshN/20WBU4Lf2/VOAHTTdOR0T1RtwAxaolr3SMo6+i9LU4g+BMnhUTkHRtIZo42XMAWVxzLgW0jTVud/TlMbGwWH20QsOnwD+rt7nlyTJbdjDbVtkK4+aI6Izc8lSLCKLh+kPezMANTkW3A5xZdJXZCtRM613arfaz2jKMlL64AFEuDfuApIneX5dbW35Ywa6Onmo+JNkL1w0k+ns8GWkUIF3uALB/nGYVJyIM8vzhpksHULHduVKmWR3fVeyXIEkrfGrIYF1PdgrDarU58dpuxPjm8J3Je+HeeRmwIDAQAB"
	API_BASE_URL   = "https://mk-api.yybip.com"
)

type Client struct {
	token string
}

// NewClient 创建新的API客户端
func NewClient() *Client {
	return &Client{}
}

// Login 登录并获取token
func (c *Client) Login(username, password string) error {
	// 解析RSA公钥
	block, _ := pem.Decode([]byte(RSA_PUBLIC_KEY))
	if block == nil {
		return fmt.Errorf("failed to parse RSA public key")
	}

	pub, err := x509.ParsePKCS1PublicKey(block.Bytes)
	if err != nil {
		return fmt.Errorf("failed to parse public key: %v", err)
	}

	// RSA加密密码
	encrypted, err := rsa.EncryptPKCS1v15(rand.Reader, pub, []byte(password))
	if err != nil {
		return fmt.Errorf("failed to encrypt password: %v", err)
	}

	// Base64编码
	encodedPassword := base64.StdEncoding.EncodeToString(encrypted)
	encryptedPassword := fmt.Sprintf("MKENC(%s)", encodedPassword)

	// 准备请求数据
	reqBody := map[string]interface{}{
		"times":    7200,
		"username": username,
		"passwd":   encryptedPassword,
	}

	jsonData, err := json.Marshal(reqBody)
	if err != nil {
		return fmt.Errorf("failed to marshal request: %v", err)
	}

	// 发送请求
	req, err := http.NewRequest("POST", API_BASE_URL+"/opservice/tenant/login", strings.NewReader(string(jsonData)))
	if err != nil {
		return fmt.Errorf("failed to create request: %v", err)
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("supplier", "sk-c52d818b08c9168b8815202bb77677f9")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("failed to send request: %v", err)
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("failed to read response: %v", err)
	}

	var result struct {
		Code int    `json:"code"`
		Flag int    `json:"flag"`
		Desc string `json:"desc"`
		Data string `json:"data"`
	}

	if err := json.Unmarshal(body, &result); err != nil {
		return fmt.Errorf("failed to unmarshal response: %v", err)
	}

	if result.Code != 0 {
		return fmt.Errorf("login failed: %s", result.Desc)
	}

	c.token = result.Data
	return nil
}

// PublishArticle 发布文章
func (c *Client) PublishArticle(article *Article) error {
	jsonData, err := json.Marshal(article)
	if err != nil {
		return fmt.Errorf("failed to marshal article: %v", err)
	}

	req, err := http.NewRequest("POST", API_BASE_URL+"/content-service/cnt_article", strings.NewReader(string(jsonData)))
	if err != nil {
		return fmt.Errorf("failed to create request: %v", err)
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("token", c.token)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("failed to send request: %v", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return fmt.Errorf("failed to read response: %v", err)
	}

	var result struct {
		Code int    `json:"code"`
		Flag int    `json:"flag"`
		Desc string `json:"desc"`
		Data string `json:"data"`
	}

	if err := json.Unmarshal(body, &result); err != nil {
		return fmt.Errorf("failed to unmarshal response: %v", err)
	}

	if result.Code != 0 {
		return fmt.Errorf("publish article failed: %s", result.Desc)
	}

	return nil
}

// Article 文章结构体
type Article struct {
	Title               string   `json:"title"`
	Content             string   `json:"content"`
	KeywordIndex        string   `json:"keyword_index"`
	PageDescribe        string   `json:"page_describe"`
	AuthorNickName      string   `json:"authorNickName"`
	CoverImg            string   `json:"coverImg"`
	Categories          []string `json:"categories"`
	RecommendList       []string `json:"recommendList"`
	VisibleRange        int      `json:"visibleRange"`
	WechatSubscribe     int      `json:"wechatSubscribe"`
	RecommendUserRegist int      `json:"recommendUserRegist"`
	Fields              []string `json:"fields"`
	Industries          []string `json:"industries"`
	Labels              []string `json:"labels"`
	OpenForTenant       bool     `json:"openForTenant"`
	Status              string   `json:"status"`
	Files               []string `json:"files"`
	LinkUrl             string   `json:"linkUrl"`
	Type                string   `json:"type"`
	PageStatus          bool     `json:"page_status"`
	PageHeadline        string   `json:"page_headline"`
}
